package com.hcjy.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hcjy.common.exception.UserNotExistException;
import com.hcjy.entity.User;
import com.hcjy.entity.vo.LoginResp;
import com.hcjy.mapper.UserMapper;
import com.hcjy.service.AuthService;
import com.hcjy.util.SmsUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 权限验证服务实现类
 * @author Guqier
 * @version 1.0
 * @date 2025/6/6 18:59
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserMapper userMapper;

    /**
     * Token过期时间
     */
    @Value("${sa-token.timeout}")
    private Integer timeout;

    @Override
    public LoginResp login(String phone, String password) {
        User currUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getPhone, phone));

        // 检查用户是否存在
        if (currUser == null) {
            throw new UserNotExistException();
        }

        //检查密码是否正确
        String s = DigestUtils.md5DigestAsHex((currUser.getSalt() + password).getBytes());
        if (!s.equals(currUser.getPassword())) {
            throw new UserNotExistException();
        }

        // 执行登录操作
        return doLogin(currUser);
    }

    private LoginResp doLogin(User currUser) {
        // 执行登录
        StpUtil.login(currUser.getId());
        // TODO: 获取用户权限

        // TODO: 缓存用户信息

        // TODO: 生成登录响应
        String token = StpUtil.getTokenValue();
        return new LoginResp().setToken(token);
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }
}
